package com.pvdnc.outguess;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;

import static android.app.Activity.RESULT_OK;

public class FilePicker {
    private static final String TAG=FilePicker.class.getSimpleName();

    private int mRequestCode;

    private Activity mActivity;
    public FilePicker(Activity activity){
        mActivity=activity;
    }

    public void open(String mime){
        if(!mMime.writable())
            throw new IllegalStateException("double-fetch");
        mMime.set(mime);
        mMime.setWritable(false);
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //任意类型文件 intent.setType("*/*");
        intent.setType(mime);
        //intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        mRequestCode=new Random().nextInt(50);
        mActivity.startActivityForResult(intent,mRequestCode);
        Log.d(TAG,"start pick for request:"+mRequestCode);
    }

    public void open(){
        open(FileCallback.MIME_ANY);
    }

    private final RWReference<String> mMime=new RWReference<>();


    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent){
        //Log.d(TAG,"onActivityResult:"+this);
        if(mMime.writable())//非当前请求时，mMime不可写
            return;
        if(requestCode!=mRequestCode)
            return;
        mMime.setWritable(true);
        if(resultCode!=RESULT_OK)
            return;
        Log.d(TAG,this+" "+"received result");
        Objects.requireNonNull(intent);
        Uri uri= intent.getData();
        Log.d(TAG,"dispatch uri:"+uri+"\nfor "+this);
        try(InputStream is=getStream(uri)) {
            for (FileCallback callback : mCallbackList) {
                is.mark(0);
                callback.onFileReceived(uri,is);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private final List<FileCallback> mCallbackList=new ArrayList<>();

    private InputStream getStream(Uri uri) throws IOException {
        return mActivity.getContentResolver().openInputStream(uri);
    }

    public void addCallback(FileCallback callback){
        mCallbackList.add(callback);
    }

    @NonNull
    @Override
    public String toString() {
        return "FilePicker{" +
                "mRequestCode=" + mRequestCode +
                ", mMime=" + mMime.get() +
                '}';
    }
}
